package gov.nist.applet.phone.ua.gui;

import gov.nist.applet.phone.ua.ChatSessionManager;
import gov.nist.applet.phone.ua.Configuration;
import gov.nist.applet.phone.ua.MessengerManager;
import gov.nist.applet.phone.ua.RegisterStatus;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import java.awt.Checkbox;
import java.awt.Component;
import java.awt.Dimension;

import javax.swing.WindowConstants;
import java.awt.Toolkit;
import javax.swing.JButton;
import java.awt.Point;
import javax.swing.ImageIcon;
import javax.swing.JTabbedPane;
import javax.swing.JList;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.Timer;

import javax.swing.ListSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.dtec.common.util.SettingUtil;
import com.dtec.resource.settingInfo.Account;
import com.dtec.resource.settingInfo.AdvanceSettings;

import java.awt.Rectangle;

public class SysConfigFrame extends JFrame {

	private static final long serialVersionUID = 1L;
	MessengerManager sipMeetingManager;
	ChatSessionManager chatSessionManager;
	AdvanceSettings advanceSettings = null;
	SysConfigFrame scfHandler = this;

	private JTabbedPane settingContent = null;

	// Account Settings

	private JPanel jpAccountSetting = null;
	private JScrollPane jspAccounts = null;
	private JList jlAccountList = null;
	private JButton jbAsAdd = null;
	private JButton jbAsEdit = null;
	private JButton jbAsDel = null;
	private JLabel[] jlAccounts = null;

	// Advance Settings

	private JPanel jpAdvanceSetting = null;
	private JCheckBox jcbEncrytionEnabled = null;

	final static int CONFIGURE_ACCOUNT = 0;
	final static int CONFIGURE_ADVANCE = 1;
	private int currentSetting = 0;
	private ArrayList<Account> accounts = null;
	private int accountSelectedIndex = 0;
	final private String accountPath = "xmlSource/ServerInfo.xml";

	/**
	 * 
	 * @param sipMeetingManager
	 * @param configuration
	 *            使用哪个功能 CONFIGURE_ACCOUNT：管理账户....
	 */
	public SysConfigFrame(MessengerManager sipMeetingManager,
			ChatSessionManager chatSessionManager, int configuration) {
		super();
		this.sipMeetingManager = sipMeetingManager;
		this.chatSessionManager = chatSessionManager;
		this.currentSetting = configuration;
		advanceSettings = SettingUtil
				.getAdvanceSettings(SettingUtil.advanceSettingsPath);
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(600, 550);
		this.setResizable(false);
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			SwingUtilities.updateComponentTreeUI(this);
		} catch (Exception exe) {
			exe.printStackTrace();
		}

		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize();
		int screenHeight = screenSize.height;
		int screenWidth = screenSize.width;
		int frameH = this.getHeight();
		int frameW = this.getWidth();
		this.setLocation((screenWidth - frameW) / 2,
				(screenHeight - frameH) / 2);

		this.setIconImage(Toolkit.getDefaultToolkit().getImage(
				getClass().getResource("/images/menu/configureIcon.png")));
		this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		this.setTitle("设置");

		this.setContentPane(getSettingContent());
	}

	/**
	 * This method initializes settingContent
	 * 
	 * @return javax.swing.JTabbedPane
	 */
	private JTabbedPane getSettingContent() {
		if (settingContent == null) {
			settingContent = new JTabbedPane();
			settingContent.addTab(
					"账户",
					new ImageIcon(getClass().getResource(
							"/images/menu/addAccount.png")),
					getJpAccountSetting(), null);
			settingContent.addTab(
					"高级",
					new ImageIcon(getClass().getResource(
							"/images/sysconfig/chatConfigureIcon.png")),
					getJpAdvanceSetting(), null);
		}
		settingContent.setSelectedIndex(this.currentSetting);
		return settingContent;
	}

	/**
	 * This method initializes jpAccountSetting
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJpAccountSetting() {
		if (jpAccountSetting == null) {
			jpAccountSetting = new JPanel();
			jpAccountSetting.setLayout(null);
			jpAccountSetting.add(getJspAccounts(), null);
			jpAccountSetting.add(getJbAsAdd(), null);
			jpAccountSetting.add(getJbAsEdit(), null);
			jpAccountSetting.add(getJbAsDel(), null);
			jpAccountSetting.add(getJbRegister(), null);
		}
		return jpAccountSetting;
	}

	/**
	 * This method initializes jpAdvanceSetting
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJpAdvanceSetting() {
		if (jpAdvanceSetting == null) {
			jpAdvanceSetting = new JPanel();
			jpAdvanceSetting.setLayout(null);
			jpAdvanceSetting.add(getJcbEncrytionEnabled());
		}
		return jpAdvanceSetting;
	}

	/**
	 * This method initializes jlAccountList
	 * 
	 * @return javax.swing.JList
	 */
	private JList getJlAccountList() {
		if (jlAccountList == null) {
			jlAccountList = new JList();
			jlAccountList
					.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
			jlAccountList.setLocation(new Point(15, 12));
			jlAccountList.setSize(new Dimension(500, 426));
			jlAccountList.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			jlAccountList.setVisible(true);
			jlAccountList.setFixedCellHeight(80);
			jlAccountList.setFixedCellWidth(500);
			jlAccountList.setCellRenderer(new MyCellRender());
			freshAccountsList();
			jlAccountList.addMouseListener(accountMouseListener);
		}
		return jlAccountList;
	}

	public JScrollPane getJspAccounts() {
		if (jspAccounts == null) {
			jspAccounts = new JScrollPane(getJlAccountList());
			jspAccounts.setLocation(new Point(15, 12));
			jspAccounts.setSize(new Dimension(560, 426));
		}
		return jspAccounts;
	}

	public void freshAccountsList() {
		jlAccountList.removeAll();
		accounts = SettingUtil.getAccounts();
		jlAccounts = new JLabel[accounts.size()];
		for (Account account : accounts) {
			JLabel container = new JLabel();
			container.setHorizontalTextPosition(0);
			container.setSize(500, 50);
			StringBuffer text = new StringBuffer("状态:");
			if (account.getDefaulAccount().equals("1")) {
				text.append("默认帐号  ");
			} else {
				text.append("非默认帐号");
			}
			text.append("          ");
			text.append("帐号信息：");
			text.append(account.getName() + "@" + account.getProxyaddress()
					+ ":" + account.getProxyport());
			container.setText(text.toString());
			jlAccounts[accounts.indexOf(account)] = container;
		}
		jlAccountList.setListData(jlAccounts);
	}

	class MyCellRender extends JLabel implements ListCellRenderer {

		@Override
		public Component getListCellRendererComponent(JList list, Object label,
				int arg2, boolean isSelected, boolean cellHasFocus) {
			setIcon(new ImageIcon(
					SysConfigFrame.class
							.getResource("/images/userstatus/account.png")));
			if (isSelected) {
				setBackground(list.getSelectionBackground());
				setForeground(list.getSelectionForeground());
			} else {
				setBackground(list.getBackground());
				setForeground(list.getForeground());
			}
			setText(((JLabel) label).getText());
			setEnabled(list.isEnabled());
			setFont(list.getFont());
			setOpaque(true);
			return this;
		}

	}

	MouseListener accountMouseListener = new MouseAdapter() {
		public void mouseClicked(MouseEvent e) {
			accountSelectedIndex = jlAccountList.locationToIndex(e.getPoint());
			// Account account = accounts.get(accountSelectedIndex);
			// if (account.getDefaulAccount().equals("1")) {
			// jbRegister.setText("下线");
			// jbRegister.setToolTipText("先将已登录的用户下线，再注册其他用户");
			// } else {
			// jbRegister.setText("注册");
			// jbRegister.setToolTipText("先将已登录的用户下线，再注册其他用户");
			// }

			if (e.getClickCount() == 2) {

			}
		}
	};

	MouseListener controlMouseListner = new MouseAdapter() {
		public void mouseClicked(MouseEvent e) {
			Account account = null;
			JLabel jl = null;
			if (!e.getSource().equals(jbAsAdd)) {
				account = accounts.get(accountSelectedIndex);
				jl = jlAccounts[accountSelectedIndex];
			}
			Configuration configuration = sipMeetingManager
					.getMessageListener().getConfiguration();
			String status = sipMeetingManager.getRegisterStatus();
			System.out.println(status);
			if (e.getSource().equals(jbRegister)) {
				if (status.equalsIgnoreCase(RegisterStatus.REGISTERED)) {
					int resp = JOptionPane.showConfirmDialog(scfHandler,
							"您须先使当前登录账户离线才能使用其他账户，使当前账户离线？", "Infomation",
							JOptionPane.OK_CANCEL_OPTION);
					if (resp == 0) {
						sipMeetingManager.unRegister();
					}
					return;
				}
				configuration.userURI = account.getName() + "@"
						+ account.getProxyaddress();
				sipMeetingManager.setUserURI(configuration.userURI);
				configuration.outboundProxy = account.getProxyaddress();
				try {
					configuration.proxyPort = Integer.parseInt(account
							.getProxyport());
				} catch (NumberFormatException nfe) {
					nfe.printStackTrace();
				}
				configuration.name = account.getName();
				configuration.password = account.getPassword();
				configuration.mediaTransport = "udp";
				sipMeetingManager.getMessageListener().resetOutBoundProxy();
				chatSessionManager.closeAllSessions();
				sipMeetingManager.register();

				/* } */

			} else if (e.getSource().equals(jbAsAdd)) {
				new ConfigurationFrame(sipMeetingManager, scfHandler)
						.setVisible(true);
			} else if (e.getSource().equals(jbAsDel)) {
				int r = JOptionPane.showConfirmDialog(scfHandler, "确认删除?", "",
						JOptionPane.YES_NO_OPTION);
				if (r == 0) {
					if (account.getName().equals(configuration.name)) {
						sipMeetingManager.unRegister();
					}
					SettingUtil.delAccount(account.getId(), accountPath);
					freshAccountsList();
				}
			} else if (e.getSource().equals(jbAsEdit)) {
				if (account.getName().equals(configuration.name)) {
					sipMeetingManager.unRegister();
				}
				new ConfigurationFrame(account, scfHandler).setVisible(true);
			}
		}

	};

	private JButton jbRegister = null;

	/**
	 * This method initializes jbAsAdd
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJbAsAdd() {
		if (jbAsAdd == null) {
			jbAsAdd = new JButton();
			jbAsAdd.setText("添加");
			jbAsAdd.setSize(new Dimension(60, 30));
			jbAsAdd.setLocation(new Point(330, 449));
			jbAsAdd.addMouseListener(controlMouseListner);
		}
		return jbAsAdd;
	}

	/**
	 * This method initializes jbAsEdit
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJbAsEdit() {
		if (jbAsEdit == null) {
			jbAsEdit = new JButton();
			jbAsEdit.setText("编辑");
			jbAsEdit.setSize(new Dimension(60, 30));
			jbAsEdit.setLocation(new Point(424, 449));
			jbAsEdit.addMouseListener(controlMouseListner);
		}
		return jbAsEdit;
	}

	/**
	 * This method initializes jbAsDel
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJbAsDel() {
		if (jbAsDel == null) {
			jbAsDel = new JButton();
			jbAsDel.setSize(new Dimension(60, 30));
			jbAsDel.setText("删除");
			jbAsDel.setLocation(new Point(514, 449));
			jbAsDel.addMouseListener(controlMouseListner);
		}
		return jbAsDel;
	}

	/**
	 * This method initializes jbRegister
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getJbRegister() {
		if (jbRegister == null) {
			jbRegister = new JButton();
			jbRegister.setLocation(new Point(235, 449));
			jbRegister.setText("注册");
			jbRegister.setSize(new Dimension(60, 30));
			jbRegister.addMouseListener(controlMouseListner);
		}
		return jbRegister;
	}

	public static void main(String[] args) {
		new SysConfigFrame(null, null, 0).setVisible(true);
	}

	public int getAccountSelectedIndex() {
		return accountSelectedIndex;
	}

	public ArrayList<Account> getAccounts() {
		return accounts;
	}

	public JLabel[] getJlAccounts() {
		return jlAccounts;
	}

	public JCheckBox getJcbEncrytionEnabled() {
		if (jcbEncrytionEnabled == null) {
			jcbEncrytionEnabled = new JCheckBox("呼叫时启用数据加密");
			jcbEncrytionEnabled.setSize(200, 30);
			jcbEncrytionEnabled.setLocation(10, 10);
			if ("1".equals(advanceSettings.getEncryptionEnable())) {
				jcbEncrytionEnabled.setSelected(true);
			}
			jcbEncrytionEnabled.addItemListener(selectChangeListener);
		}
		return jcbEncrytionEnabled;
	}

	SelectionStatusChangeListener selectChangeListener = new SelectionStatusChangeListener();

	class SelectionStatusChangeListener implements ItemListener {
		@Override
		public void itemStateChanged(ItemEvent e) {
			if (e.getSource().equals(jcbEncrytionEnabled)) {
				String enabledString = "0";
				if (jcbEncrytionEnabled.isSelected()) {
					enabledString = "1";
				}
				Configuration.advanceSettings
						.setEncryptionEnable(enabledString);
				advanceSettings.setEncryptionEnable(enabledString);
				SettingUtil.setAdvanceSettings(advanceSettings,
						SettingUtil.advanceSettingsPath);

			}
		}

	}
}
